package com.example.manage_dzensaas.core.utils;

import com.example.manage_dzensaas.core.enums.ChannelNoEnum;
import com.example.manage_dzensaas.filter.exception.CustomException;
import org.apache.commons.codec.digest.DigestUtils;
import org.noear.solon.annotation.Component;

import java.nio.charset.StandardCharsets;

@Component
public class SignUtils {

    /**
     * 生成签名
     * @param channelNo 渠道号
     * @param timestamp 时间戳
     * @param secretKey 渠道密钥
     * @return 签名
     */
    public static String generateSign(String channelNo, long timestamp, String secretKey) {
        // 修复字符串格式化参数数量不匹配问题
        String rawString = "channel_no" + channelNo + "timestamp" + timestamp + secretKey;
            
        try {
            // 将SHA1结果转换为十六进制字符串
            String sha1Hex = DigestUtils.sha1Hex(rawString);
            // 再进行MD5加密
            return DigestUtils.md5Hex(sha1Hex.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new CustomException("签名异常");
        }
    }

    /**
     * 验证签名
     * @param channelNo 渠道号
     * @param timestamp 时间戳
     * @param sign 待验证的签名
     * @return 是否验证通过
     */
    public static boolean verifySign(String channelNo, long timestamp, String sign) {
        // 基本参数校验
        if (channelNo == null || sign == null) {
            return false;
        }

        ChannelNoEnum channel = ChannelNoEnum.getByCode(channelNo);
        if (channel == null || channel.getSecretKey() == null) {
            return false;
        }
        
        String expectedSign = generateSign(channelNo, timestamp, channel.getSecretKey());
        return expectedSign.equalsIgnoreCase(sign);
    }
}
